package com.java.compilation;

import com.java.compilation.helper.XmlWriter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JackAnalyzer {
    private List<File> jackFiles = new ArrayList<>();

    public JackAnalyzer(File... files) {
        Arrays.stream(files).forEach(jackFiles::add);
    }

    public void analyze() throws IOException, IllegalAccessException {
        for (File jackFile : jackFiles) {
            File xmltFile = createXMLTFile(jackFile);
            outputXmlTFile(jackFile, xmltFile);
            new CompilationEngine_10(new JackTokenizer(jackFile),createXMLFile(jackFile));
        }

    }

    private static void outputXmlTFile(File jackFile, File xmltFile) throws IOException {
        XmlWriter xmlTWriter = new XmlWriter(xmltFile);
        JackTokenizer tokenizer = new JackTokenizer(jackFile);
        xmlTWriter.println("<tokens>");
        while (tokenizer.hasMoreTokens()) {
            tokenizer.advance();
            xmlTWriter.println(tokenizer);
        }

        xmlTWriter.println("</tokens>");
        xmlTWriter.close();
    }

    private static File createXMLTFile(File jackFile) {
        String xml = jackFile.getName().replace("jack", "xml").replace(".", "T-1.");
        return jackFile.toPath().resolveSibling(xml).toFile();
    }

    private static File createXMLFile(File jackFile) {
        String xml = jackFile.getName().replace("jack", "xml");
        return jackFile.toPath().resolveSibling(xml).toFile();
    }
}
